/**
 * 班次模态框组件
 */

import { useState, useEffect } from 'react'
import type { PluginComponentProps, Shift, Employee } from '../../types'
import { createShift, updateShift as apiUpdateShift, deleteShift } from '../../api'
import { toast } from '../../utils/toast'
import './styles.css'

export function ShiftModal({ context }: PluginComponentProps) {
  const [isOpen, setIsOpen] = useState(false)
  const [employees, setEmployees] = useState<Employee[]>([])
  const [editingShift, setEditingShift] = useState<Shift | null>(null)
  const [defaultEmployeeId, setDefaultEmployeeId] = useState<string | number>('')
  const [defaultDate, setDefaultDate] = useState('')

  const [formData, setFormData] = useState({
    employeeId: '',
    date: '',
    type: 'morning' as const,
    note: '',
  })

  useEffect(() => {
    setEmployees(context.getEmployees())

    // 监听添加班次事件
    const unsubAdd = context.on('ui:add-shift', () => {
      setEditingShift(null)
      setIsOpen(true)
    })

    // 监听编辑班次事件（从班次点击）
    const unsubEdit = context.on('shift:click', (shift: Shift) => {
      setEditingShift(shift)
      setFormData({
        employeeId: String(shift.employeeId),
        date: shift.date,
        type: shift.type,
        note: shift.note || '',
      })
      setIsOpen(true)
    })

    // 监听单元格点击（直接添加）
    const unsubCell = context.on(
      'cell:click',
      (data: { employeeId: string | number; date: string }) => {
        console.log('📩 ShiftModal 收到 cell:click:', data)

        // 检查该单元格是否已有班次
        const existingShift = context
          .getShifts()
          .find(s => s.employeeId === data.employeeId && s.date === data.date)

        console.log('🔍 现有班次:', existingShift)

        if (!existingShift) {
          console.log('➕ 打开添加班次模态框')
          setDefaultEmployeeId(data.employeeId)
          setDefaultDate(data.date)
          setFormData({
            employeeId: String(data.employeeId),
            date: data.date,
            type: 'morning',
            note: '',
          })
          setEditingShift(null)
          setIsOpen(true)
        } else {
          console.log('ℹ️ 该单元格已有班次，不打开模态框')
        }
      }
    )

    return () => {
      unsubAdd()
      unsubEdit()
      unsubCell()
    }
  }, [context])

  // 当模态框打开且没有编辑班次时，使用默认值
  useEffect(() => {
    if (isOpen && !editingShift) {
      setFormData(prev => ({
        ...prev,
        employeeId: defaultEmployeeId ? String(defaultEmployeeId) : prev.employeeId,
        date: defaultDate || prev.date,
      }))
    }
  }, [isOpen, editingShift, defaultEmployeeId, defaultDate])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    try {
      if (editingShift) {
        // 更新现有班次 - 先调用 API
        console.log('📝 更新班次到 API:', editingShift.id)
        const updated = await apiUpdateShift(editingShift.id, {
          employeeId: formData.employeeId,
          date: formData.date,
          type: formData.type,
          note: formData.note,
        })

        // 然后更新本地状态
        context.updateShift(editingShift.id, updated)
        console.log('✅ 班次更新成功')

        // 通知外部刷新数据
        if ((window as any).refreshScheduleData) {
          setTimeout(() => (window as any).refreshScheduleData(), 100)
        }
      } else {
        // 添加新班次 - 先调用 API
        const employee = employees.find(emp => String(emp.id) === formData.employeeId)
        console.log('➕ 添加班次到 API:', formData)

        const created = await createShift({
          employeeId: formData.employeeId,
          employeeName: employee?.name,
          date: formData.date,
          type: formData.type,
          note: formData.note,
          status: 'confirmed',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        })

        // 然后添加到本地状态
        context.addShift(created)
        console.log('✅ 班次添加成功:', created)

        // 通知外部刷新数据
        if ((window as any).refreshScheduleData) {
          setTimeout(() => (window as any).refreshScheduleData(), 100)
        }
      }

      handleClose()
      toast.success(editingShift ? '班次更新成功' : '班次添加成功')
    } catch (error) {
      console.error('❌ 保存班次失败:', error)
      toast.error('保存失败，请检查服务器是否正常运行')
    }
  }

  const handleDelete = async () => {
    if (!editingShift) return

    toast.confirm({
      title: '确认删除',
      message: '确定要删除这个班次吗？此操作无法撤销。',
      confirmText: '删除',
      cancelText: '取消',
      onConfirm: async () => {
        try {
          console.log('🗑️ 删除班次:', editingShift.id)

          // 先调用 API 删除
          await deleteShift(editingShift.id)

          // 然后从本地状态删除
          context.removeShift(editingShift.id)
          console.log('✅ 班次删除成功')

          // 通知外部刷新数据
          if ((window as any).refreshScheduleData) {
            setTimeout(() => (window as any).refreshScheduleData(), 100)
          }

          handleClose()
          toast.success('班次删除成功')
        } catch (error) {
          console.error('❌ 删除班次失败:', error)
          toast.error('删除失败，请检查服务器是否正常运行')
        }
      },
    })
  }

  const handleClose = () => {
    setIsOpen(false)
    setEditingShift(null)
    setDefaultEmployeeId('')
    setDefaultDate('')
    setFormData({
      employeeId: '',
      date: '',
      type: 'morning',
      note: '',
    })
  }

  if (!isOpen) return null

  return (
    <div className="modal-overlay" onClick={handleClose}>
      <div className="modal-content" onClick={e => e.stopPropagation()}>
        <div className="modal-header">
          <h3>{editingShift ? '编辑班次' : '添加班次'}</h3>
          <button className="modal-close" onClick={handleClose}>
            ×
          </button>
        </div>

        <form className="modal-body" onSubmit={handleSubmit}>
          <div className="form-group">
            <label htmlFor="employee">员工</label>
            <select
              id="employee"
              className="form-control"
              value={formData.employeeId}
              onChange={e => setFormData({ ...formData, employeeId: e.target.value })}
              required
            >
              <option value="">请选择员工</option>
              {employees.map(emp => (
                <option key={emp.id} value={emp.id}>
                  {emp.name}
                </option>
              ))}
            </select>
          </div>

          <div className="form-group">
            <label htmlFor="date">日期</label>
            <input
              type="date"
              id="date"
              className="form-control"
              value={formData.date}
              onChange={e => setFormData({ ...formData, date: e.target.value })}
              required
            />
          </div>

          <div className="form-group">
            <label htmlFor="type">班次类型</label>
            <select
              id="type"
              className="form-control"
              value={formData.type}
              onChange={e => setFormData({ ...formData, type: e.target.value as any })}
              required
            >
              <option value="morning">早班 (08:00-16:00)</option>
              <option value="afternoon">中班 (16:00-24:00)</option>
              <option value="night">夜班 (00:00-08:00)</option>
            </select>
          </div>

          <div className="form-group">
            <label htmlFor="note">备注</label>
            <textarea
              id="note"
              className="form-control"
              rows={3}
              value={formData.note}
              onChange={e => setFormData({ ...formData, note: e.target.value })}
              placeholder="可选"
            />
          </div>

          <div className="modal-footer">
            {editingShift && (
              <button type="button" className="btn btn-danger" onClick={handleDelete}>
                删除
              </button>
            )}
            <div className="modal-actions">
              <button type="button" className="btn btn-secondary" onClick={handleClose}>
                取消
              </button>
              <button type="submit" className="btn btn-success">
                {editingShift ? '保存' : '添加'}
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>
  )
}
